package com.boomsecret.algorithm;

import java.util.Objects;

/**
 * @author wangjinliang on 2019/1/16.
 */
public class BubbleSortDemo {
    public static void main(String[] args) {
        int[] array01 = {4, 3, 4, 1};
        informalBubbleSort(array01);

        System.out.println("---------");

        int[] array02 = {3, 4, 1, 2};
        formalBubbleSort(array02);

        System.out.println("---------");

        int[] array03 = {3, 4, 1, 2};
        optimalBubbleSort(array03);
    }

    /**
     * 3.正式冒泡排序 改变>/< 就可以改变大小顺序 对formalBubbleSort做了优化
     */
    private static void optimalBubbleSort(int[] array) {
        if (Objects.isNull(array)) {
            throw new RuntimeException("array is null");
        }
        print(array);
        int temp;
        // 代表轮询次数 次数总是length-1
        for (int i = 1; i < array.length; i ++) {
            int key = 0;
            for (int j = 0; j < array.length - i; j ++) {
                if (array[j] > array[j + 1]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    key = 1;
                }
            }
            if (key == 0) {
                break;
            }
            print(array);
        }
    }

    /**
     * 2.正式冒泡排序 改变>/< 就可以改变大小顺序
     */
    private static void formalBubbleSort(int[] array) {
        if (Objects.isNull(array)) {
            throw new RuntimeException("array is null");
        }
        print(array);
        int temp;
        // 代表轮询次数 次数总是length-1
        for (int i = 1; i < array.length; i ++) {
            for (int j = 0; j < array.length - i; j ++) {
                if (array[j] > array[j + 1]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
            print(array);
        }
    }

    /**
     * 1.非正式冒泡排序 改变>/< 就可以改变大小顺序
     */
    private static void informalBubbleSort(int[] array) {
        if (Objects.isNull(array)) {
            throw new RuntimeException("array is null");
        }
        print(array);
        int temp;
        for (int i = 0; i < array.length - 1; i ++) {
            for (int j = i + 1; j < array.length; j ++) {
                if (array[i] > array[j]) {
                    temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                }
            }
            print(array);
        }
    }

    private static void print(int[] array) {
        if (Objects.isNull(array)) {
            throw new RuntimeException("array is null");
        }
        for (int item : array) {
            System.out.print(item + " ");
        }
        System.out.println();
    }
}
